import axios from 'axios';
import { ElMessage } from 'element-plus';

const request = axios.create({
    baseURL: import.meta.env.VITE_APP_BASE_API,
    timeout: 5000
});

import useUserStore from '../store/modules/user';
import pinia from "@/store";
request.interceptors.request.use(config => {
    const userStore = useUserStore(pinia);
    if (userStore.token) {
        config.headers['token'] = userStore.token;
    }
    return config;
}, error => {
    Promise.reject(error);
});

request.interceptors.response.use(
    response => {
        return response.data;
    },
    error => {
        let message = '';
        switch (error.response.status) {
            case 401:
                message = 'TOKEN失效，请重新登录';
                break;
            case 403:
                message = '未授权，请登录';
                break;
            case 404:
                message = '请求地址有误';
                break;
            case 500:
                message = '服务器异常';
                break;
            default:
                message = '网络异常';
                break;
        }

        ElMessage({
            message,
            type: 'error'
        })

        return Promise.reject(error);
    }
);

export default request;